package com.laiketui.admin.store.service.dubbo.productClass;


import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laiketui.admin.store.api.productClass.ProductClassService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.mapper.ProductClassMapper;
import com.laiketui.common.utils.tool.ImgUploadUtils;
import com.laiketui.common.utils.tool.StringUtils;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.domain.index.IndexData;
import com.laiketui.domain.index.IndexItem;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.mch.AdminModel;
import com.laiketui.domain.productClass.ProductClass;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.domain.vo.productClass.ProductClassVo;
import org.apache.dubbo.common.utils.CIDRUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 34496
 * @description 针对表【lkt_product_class(商品分类)】的数据库操作Service实现
 * @createDate 2025-01-10 10:16:45
 */
@Service
public class ProductClassServiceImpl implements ProductClassService {

    //珞珂家居商城id
    private static final int defaultStoreId = 1;

    //顶级等级
    private static final int topClassLevel = 0;

    //一级分类
    private static final int firstClassLevel = 1;

    //二级分类
    private static final int secondClassLevel = 2;

    //显示
    private static final int isDisplay = 1;

    @Autowired
    private ProductClassMapper productClassMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private RedisUtil redisUtil;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertProductClass(ProductClassVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        Integer storeId = vo.getStoreId();
        ProductClass productClass = this.selectTopProductClass(storeId);
        Integer topCid = null;
        if (productClass == null) {
            topCid = this.createTopClass(storeId);
        } else {
            topCid = productClass.getCid();
        }
        ProductClass insertClass = new ProductClass();
        insertClass.setSid(topCid);
        if (StringUtil.isNotBlank(vo.getImg())) {
            insertClass.setImg(ImgUploadUtils.getUrlImgByName(vo.getImg(), true));
        }
        insertClass.setPname(vo.getPname());
        insertClass.setLevel(firstClassLevel);
        insertClass.setSort(vo.getSort());
        insertClass.setStoreId(vo.getStoreId());
        insertClass.setAddDate(new Date());
        insertClass.setIsDisplay(isDisplay);
        productClassMapper.insertSelective(insertClass);
        String childsJson = vo.getChilds();
        List<ProductClass> childs = JSONObject.parseObject(childsJson, new TypeReference<List<ProductClass>>() {
        });
        childs.forEach(child -> {
            ProductClass childProductClass = new ProductClass();
            childProductClass.setSid(insertClass.getCid());
            childProductClass.setPname(child.getPname());
            childProductClass.setSort(child.getSort());
            childProductClass.setImg(ImgUploadUtils.getUrlImgByName(vo.getImg(), true));
            childProductClass.setLevel(secondClassLevel);
            childProductClass.setStoreId(vo.getStoreId());
            childProductClass.setAddDate(new Date());
            childProductClass.setIsDisplay(isDisplay);
            productClassMapper.insertSelective(childProductClass);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductClass(ProductClassVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        ProductClass updateClass = new ProductClass();
        updateClass.setCid(vo.getCid());
        if (StringUtil.isNotBlank(vo.getImg())) {
            updateClass.setImg(ImgUploadUtils.getUrlImgByName(vo.getImg(), true));
        }
        updateClass.setPname(vo.getPname());
        updateClass.setLevel(firstClassLevel);
        updateClass.setSort(vo.getSort());
        updateClass.setStoreId(vo.getStoreId());
        updateClass.setAddDate(new Date());
        updateClass.setIsDisplay(isDisplay);
        productClassMapper.updateByPrimaryKeySelective(updateClass);
        String childsJson = vo.getChilds();
        List<ProductClass> childs = JSONObject.parseObject(childsJson, new TypeReference<List<ProductClass>>() {
        });
        List<ProductClass> nonNullIdList = new ArrayList<>();
        childs.forEach(child -> {
            //查询子级列表
            List<ProductClass> childClassList = this.getChildClassList(updateClass.getCid());

            Integer id = child.getCid();
            ProductClass childProductClass = new ProductClass();
            if (id == null) {
                childProductClass.setSid(updateClass.getCid());
                childProductClass.setPname(child.getPname());
                childProductClass.setSort(child.getSort());
                if (StringUtil.isNotBlank(child.getImg())) {
                    childProductClass.setImg(ImgUploadUtils.getUrlImgByName(child.getImg(), true));
                }
                childProductClass.setLevel(secondClassLevel);
                childProductClass.setStoreId(vo.getStoreId());
                childProductClass.setAddDate(new Date());
                childProductClass.setIsDisplay(isDisplay);
                productClassMapper.insertSelective(childProductClass);
                nonNullIdList.add(childProductClass);
            } else {
                childProductClass.setCid(id);
                childProductClass.setPname(child.getPname());
                childProductClass.setSort(child.getSort());
                if (StringUtil.isNotBlank(child.getImg())) {
                    childProductClass.setImg(ImgUploadUtils.getUrlImgByName(child.getImg(), true));
                }
                childProductClass.setStoreId(vo.getStoreId());
                productClassMapper.updateByPrimaryKeySelective(childProductClass);
                nonNullIdList.add(childProductClass);
            }
        });
        //查询子级列表
        this.deleteNotExistClass(nonNullIdList, updateClass.getCid());
    }

    @Override
    public ProductClass selectInfo(ProductClassVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        ProductClass productClass = new ProductClass();
        productClass.setCid(vo.getCid());
        productClass = productClassMapper.selectOne(productClass);
        productClass.setImg(publiceService.getImgPath(productClass.getImg(), defaultStoreId));
        //查出子级分类
        int storeId = vo.getStoreId();
        Example example = new Example(ProductClass.class);
        example.createCriteria().andEqualTo("recycle", GloabConst.RecycleType.NOT_RECYCLE)
                .andEqualTo("storeId", storeId)
                .andEqualTo("level", secondClassLevel)
                .andEqualTo("isDisplay", isDisplay)
                .andEqualTo("sid",vo.getCid());
        List<ProductClass> productClassList = productClassMapper.selectByExample(example);
        productClassList.forEach(p -> {
            String img = p.getImg();
            img = publiceService.getImgPath(img, defaultStoreId);
            p.setImg(img);
        });
        productClass.setChilds(productClassList);
        return productClass;
    }

    @Override
    public PageInfo<ProductClass> selectList(MainVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        Example example = new Example(ProductClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("level", firstClassLevel);
        criteria.andEqualTo("storeId", vo.getStoreId());
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<ProductClass> list = productClassMapper.selectByExample(example);
        list.forEach(p -> {
            p.setImg(publiceService.getImgPath(p.getImg(), defaultStoreId));
        });
        PageInfo<ProductClass> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public int deleteProductClass(ProductClassVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        ProductClass productClass = new ProductClass();
        productClass.setCid(vo.getCid());
        int i = productClassMapper.delete(productClass);
        ProductClass params = new ProductClass();
        params.setSid(vo.getCid());
        List<ProductClass> classes = productClassMapper.select(params);
        classes.forEach(c -> {
            ProductClass deleteClass = new ProductClass();
            deleteClass.setCid(c.getCid());
            productClassMapper.delete(deleteClass);
        });
        return i;
    }

    @Override
    public int updateStatus(ProductClassVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        ProductClass productClass = new ProductClass();
        productClass.setCid(vo.getCid());
        productClass = productClassMapper.selectOne(productClass);
        Integer recycle = productClass.getRecycle();
        if (DictionaryConst.ProductRecycle.NOT_STATUS.equals(recycle)) {
            productClass.setRecycle(DictionaryConst.ProductRecycle.RECOVERY);
        }
        if (DictionaryConst.ProductRecycle.RECOVERY.equals(recycle)) {
            productClass.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
        }
        int i = productClassMapper.updateByPrimaryKeySelective(productClass);
        ProductClass params = new ProductClass();
        params.setSid(productClass.getCid());
        List<ProductClass> childs = productClassMapper.select(params);
        Integer updateRecycle = productClass.getRecycle();
        childs.forEach(child -> {
            ProductClass childClass = new ProductClass();
            childClass.setCid(child.getCid());
            childClass.setRecycle(updateRecycle);
            productClassMapper.updateByPrimaryKeySelective(childClass);
        });
        return i;
    }

    //查询顶级分类
    private ProductClass selectTopProductClass(Integer storeId) {
        ProductClass productClass = null;
        if (storeId == null) {
            throw new LaiKeAPIException("storeId不存在");
        }
        Example example = new Example(ProductClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId", storeId)
                .andEqualTo("level", topClassLevel);
        List<ProductClass> classes = productClassMapper.selectByExample(example);
        if (classes.size() > 0) {
            productClass = classes.get(0);
        }
        return productClass;
    }

    //新增顶级分类
    private Integer createTopClass(Integer storeId) {
        if (storeId == null) {
            throw new LaiKeAPIException("storeId不存在");
        }
        ProductClass productClass = null;
        Example example = new Example(ProductClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId", defaultStoreId)
                .andEqualTo("level", topClassLevel);
        List<ProductClass> classList = productClassMapper.selectByExample(example);
        if (classList.size() > 0) {
            productClass = classList.get(0);
        }
        ProductClass newClass = new ProductClass();
        BeanUtils.copyProperties(productClass, newClass);
        newClass.setCid(null);
        newClass.setStoreId(storeId);
        productClassMapper.insertSelective(newClass);
        return newClass.getCid();
    }

    //查出子级分类
    public List<ProductClass> getChildClassList(Integer sid) {
        ProductClass productClass = new ProductClass();
        productClass.setSid(sid);
        List<ProductClass> childs = productClassMapper.select(productClass);
        return childs;
    }

    //删除不存在分类
    private void deleteNotExistClass(List<ProductClass> classList, Integer sid) {
        if (sid == null || classList.size() < 1) {
            return;
        }
        List<ProductClass> allChildClassList = this.getChildClassList(sid);
        List<ProductClass> notExistClassList = new ArrayList<>();
        for (ProductClass child : allChildClassList) {
            int mark = 0;
            for (ProductClass productClass : classList) {
                if (child.getCid().equals(productClass.getCid())) {
                    mark++;
                }
            }
            if (mark == 0) {
                notExistClassList.add(child);
            }
        }
        notExistClassList.forEach(item -> {
            ProductClass productClass = new ProductClass();
            productClass.setCid(item.getCid());
            productClassMapper.delete(productClass);
        });
    }


}




